﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.IdentityModel.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;

namespace XYZ.Acknowledge
{
    public class UserProfileCheck : IHttpModule
    {
        public UserProfileCheck() 
        { 
        }

        public void Init(HttpApplication app)
        {
            // Hook into Release Request
            app.ReleaseRequestState += (new EventHandler(this.ReleaseRequest_Handler));
            //app.PreRequestHandlerExecute += new EventHandler(this.PreRequestHandlerExecute_Handler);

        }

        private void ReleaseRequest_Handler(object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;

            if (!app.Request.RawUrl.ToLower().Contains("acknowledge.aspx"))
            {
                //context.Response.Write("<h1><font color=red>" + "UserProfileCheckModule: Release Request State" + "</font></h1><hr>");

                string originatingUrl = app.Request.Url.ToString();
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                    SPWeb currentWeb = site.RootWeb;
                    SPUser currentUser = SPContext.Current.Web.CurrentUser;
                       
                    //Create a new UserProfileManager
                    UserProfileManager pManager = new UserProfileManager(serviceContext);
                    //Get the User Profile for the current user
                    try
                    {
                        //don't want to check service accounts or users with full control
                        if (!(currentUser.IsSiteAuditor))
                        {
                            UserProfile uProfile = pManager.GetUserProfile(currentUser.LoginName);
                            //check if policy was acknowledged
                            if (uProfile["XYZENACKNOW"].Value.Equals(false))
                            {
                                //if not, popup acknowledgement in modal window, sharepoint modal javascript function
                                //showacknowdialog must be included in your master page, preferably via scriptlink control,                                 
                                //for this to work
                                Page page = HttpContext.Current.CurrentHandler as Page; 
                                if (page != null)
                                {
                                    StringBuilder sb = new StringBuilder();
                                    sb.Append("<script type='text/javascript'>");
                                    sb.Append("ExecuteOrDelayUntilScriptLoaded(ShowAcknowDialog, \"sp.js\");");
                                    sb.Append("</script>");

                                    string newscript = sb.ToString();
                                    
                                    app.Response.Write(newscript); 
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("XYZENACKNOW", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                    }
                }
            }
        }

        public void Dispose() { }
    }
}
